package mxmf.utils;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Component
public class FreeMarkHelper {

    private static final Logger logger = LoggerFactory.getLogger(FreeMarkHelper.class);

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     *
     * @param templatName  ${folderName}/templateName
     * @param obj
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public String merge(String templatName, Object obj) throws IOException, TemplateException {
        try {
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatName);
            template.setOutputEncoding("UTF-8");
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, obj);
            return content;
        } catch (IOException | TemplateException e) {
            logger.error(e.toString(), e);
            throw e;
        }
    }

}
